package com.nx.biz.shopify.support;

import com.nx.biz.shopify.api.bo.ShopifySession;
import com.nx.biz.shopify.model.predicate.ShopifySessionPredicate;
import com.nx.biz.shopify.repo.ShopifySessionRepository;
import com.nx.common.tools.CheckTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ShopifyContext {

    @Resource
    private ShopifySessionRepository shopifySessionRepository;

    /**
     * API版本
     */
    private String apiVersion = "2024-07";

    // 不允许new
    private ShopifyContext() {

    }

    /**
     * 获取商店的会话
     */
    public ShopifySession getMatchSession(String shopDomain) {
        // 1) 查询db数据
        ShopifySessionPredicate shopifySessionPredicate = new ShopifySessionPredicate();
        shopifySessionPredicate.setEqShop(shopDomain);
        List<ShopifySession> shopifySessionList = shopifySessionRepository.queryList(shopifySessionPredicate);
        if (CheckTools.isNullOrEmpty(shopifySessionList)) {
            log.error("-> [shopify-context]获取会话信息失败...error，错误信息：匹配shopDomain：{}的session为空", shopDomain);
            return null;
        }
        // 2) 返回匹配的会话
        ShopifySession shopifySessionFirst = shopifySessionList.get(0);
        return shopifySessionFirst;
    }

    /**
     * 获取商店的会话
     */
    public String getMatchAccessToken(String shopDomain) {
        // 1) 获取会话
        ShopifySession matchSession = this.getMatchSession(shopDomain);
        if (CheckTools.isNullOrEmpty(matchSession)) {
            log.error("-> [shopify-context]获取访问令牌失败...error，错误信息：匹配shopDomain：{}的session为空", shopDomain);
            return null;
        }
        String accessToken = matchSession.getAccessToken();
        if (CheckTools.isNullOrEmpty(accessToken)) {
            log.error("-> [shopify-context]获取访问令牌失败...error，错误信息：令牌为空");
            return null;
        }
        return accessToken;
    }

    /**
     * 获取API版本
     * todo 如果shopify是每个月发一个版，这边可以做一些逻辑默认取当月
     */
    public String getApiVersion() {
        return apiVersion;
    }

    public String buildFullUrl(String url, String shopName) {
        return String.format(url, shopName, apiVersion);
    }

    /* ------------------------------------------------------------------------------------------------------------ */

    /**
     * webhook是否注册完成
     */
    private Map<String, Boolean> webhookRegisterCompleteMap = new HashMap<>();

    public void setWebhookRegisterCompleted(String shopDomain) {
        this.webhookRegisterCompleteMap.put(shopDomain, true);
    }

    public Boolean getWebhookRegisterComplete(String shopDomain) {
        Boolean b = this.webhookRegisterCompleteMap.get(shopDomain);
        if (CheckTools.isNullOrEmpty(b)) {
            return false;
        }
        return b;
    }

}